﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection.Emit;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace Simple.Common.Core.Attributes
{
    /// <summary>
    /// 权限授权验证
    /// </summary>
    [AttributeUsage(AttributeTargets.Method)]
    public class SignatureAttribute : ActionFilterAttribute, IFilterMetadata
    {
        /// <summary>
        /// 允许误差时间（秒）
        /// </summary>
        public int second { get; }


        /// <summary>
        /// 要求签名
        /// </summary>
        /// <param name="second">签名允许误差时间，单位：秒，默认600秒，10分钟</param>
        public SignatureAttribute(int second = 600)
        {
            this.second = second;
        }

        /// <summary>
        /// 签名验证
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
#if DEBUG
            //DEBUG模式不验签名
            base.OnActionExecuting(filterContext);
            return;
#endif

            var request = filterContext.HttpContext.Request;
            var isSignOK = false;
            //签名
            var signature = request.Headers["signature"].ToString();
            //时间戳
            var timestamp = request.Headers["timestamp"].ToString();
            //获取token
            var claim = filterContext.HttpContext.User.Claims.FirstOrDefault(m => m.Type == "sub");
            var userId = claim == null ? Guid.Empty : Guid.Parse(claim.Value);
            if (userId != Guid.Empty)
            {
                base.OnActionExecuting(filterContext);
                return;
            }
            string signKey = GetSignKey(DateTime.Now);

            SignatureHelper signHelper = new SignatureHelper();
            if (request.Method.ToUpper() == "GET")
            {
                var getCollection = request.Query;
                isSignOK = signHelper.CheckSignature(getCollection, signKey, signature, timestamp, second);
                if (!isSignOK)
                    throw new Exception($"签名无效：参数={JsonConvert.SerializeObject(getCollection)}");
            }
            else
            {
                request.Body.Position = 0;
                var bodyStr = "";
                using (StreamReader stream = new StreamReader(request.Body))
                {
                    bodyStr = stream.ReadToEnd();
                    request.Body.Position = 0;
                }
                var bodyStrDic = JsonConvert.DeserializeObject<Dictionary<string, object>>(bodyStr);
                bodyStrDic.Add("signature", signature);
                bodyStrDic.Add("timestamp", timestamp);
                isSignOK = signHelper.CheckSignature(bodyStrDic, signKey, second);
                if (!isSignOK)
                    throw new Exception($"签名无效：参数={JsonConvert.SerializeObject(bodyStrDic)}");
            }
            if (!isSignOK)
            {
                string ErrMsg = string.IsNullOrEmpty(signHelper.ErrMsg) ? "签名无效" : signHelper.ErrMsg;
                //返回签名校验失败
                filterContext.Result = GetErrorResult(ErrMsg);
                return;
            }
            base.OnActionExecuting(filterContext);
        }

        /// <summary>
        /// 错误提示
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        private IActionResult GetErrorResult(string msg)
        {
            return new ContentResult() {Content = msg};
            //return  JsonResult(new ResultEntity<Object>() { IsSuccess = false, Msg = msg, Data = null });
        }

        /// <summary>
        /// 获取签名Key
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        private string GetSignKey(DateTime date)
        {
            string signKey = "hys" + date.ToString("MMdd");
            return signKey;
        }
    }
}
